"""
./myenv/Scripts/python fujian1_origin_gragh.py
"""


import os
import json
import matplotlib.pyplot as plt
from datetime import datetime

# 定义路径
input_dir = 'fujian/fujian1/group_output'
output_dir = os.path.join(input_dir, 'graph')
os.makedirs(output_dir, exist_ok=True)

# 遍历每个 JSON 文件
for filename in os.listdir(input_dir):
    if filename.endswith('.json'):
        file_path = os.path.join(input_dir, filename)
        
        # 读取 JSON 数据
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # 提取日期和库存数据
        dates = [datetime.strptime(item['date'], '%Y-%m-%d') for item in data]
        inventory = [item['inventory'] for item in data]
        
        # 绘制图表
        plt.figure()
        plt.plot(dates, inventory, marker='o', linestyle='-', color='b')
        
        # 设置图表标题和标签
        category_name = filename.replace('inventory_category', '').replace('.json', '')
        plt.title(f'Inventory Trend for Category {category_name}')
        plt.xlabel('Month')
        plt.ylabel('Inventory')
        
        # 设置横轴格式化仅显示月份
        plt.gca().xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%Y-%m'))
        plt.xticks(rotation=45)
        
        # 保存图表
        output_path = os.path.join(output_dir, f'{category_name}_inventory_trend.png')
        plt.savefig(output_path, bbox_inches='tight')
        plt.close()
        
        print(f'Saved plot for category {category_name} to {output_path}')